/*
 * Copyright (C) 2005, Velocityme Partnership
 * SignedLicenceKey.java
 *
 * Created on 07 July 2005, 09:34
 */

package com.velocityme.utility;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.security.*;
import java.util.zip.DataFormatException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author  Robert
 */

public final class SignedLicenceKey implements Serializable {

    private byte[] m_content;
    private byte[] m_signature;
    
    public SignedLicenceKey(LicenceKey p_licenceKey, PrivateKey p_signingKey, Signature p_signingEngine)
	throws IOException, java.security.InvalidKeyException, SignatureException {
	    // creating a stream pipe-line, from a to b
	    ByteArrayOutputStream b = new ByteArrayOutputStream();
            XMLEncoder a = new XMLEncoder(b);
	    
	    // write and flush the object content to byte array
	    a.writeObject(p_licenceKey);
	    a.flush();
	    a.close();
            m_content = b.toByteArray();
	    b.close();
	    
	    // now sign the encapsulated object
	    this.sign(p_signingKey, p_signingEngine);
    }
    
    public SignedLicenceKey() {
    }
    
    public String getContent() {
        return (m_content == null)? null: new BASE64Encoder().encode(m_content); 
    }
    
    public void setContent(String p_content) {
        try {
            m_content = (p_content == null)? null: new BASE64Decoder().decodeBuffer(p_content); 
        } catch(IOException e) {
        }
    }
    
    public String getSignature() {
        return (m_signature == null)? null: new BASE64Encoder().encode(m_signature); 
    }
    
    public void setSignature(String p_signature) {
        try {
            m_signature = (p_signature == null)? null: new BASE64Decoder().decodeBuffer(p_signature); 
        } catch(IOException e) {
        }
    }

    public LicenceKey getLicenceKey() throws IOException, ClassNotFoundException {
	// creating a stream pipe-line, from b to a
	ByteArrayInputStream b = new ByteArrayInputStream(m_content);
        XMLDecoder a = new XMLDecoder(b);
	LicenceKey licenceKey = (LicenceKey)a.readObject();
	b.close();
	a.close();
	return licenceKey;
    }

    public boolean verify(PublicKey verificationKey, Signature verificationEngine)
	throws java.security.InvalidKeyException, SignatureException {
	    verificationEngine.initVerify(verificationKey);
            verificationEngine.update(m_content);
            return verificationEngine.verify(m_signature);
     }

    private void sign(PrivateKey signingKey, Signature signingEngine)
	throws IOException, java.security.InvalidKeyException, SignatureException {
	    // initialize the signing engine
	    signingEngine.initSign(signingKey);
	    signingEngine.update(m_content);
	    m_signature = signingEngine.sign();
    }

}
